package com.chenchao.javacommonclass;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/12 10:43
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.commonclass.MyDateUtil.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 日期工具类
 * 日期转成字符串
 * 字符串转成日期
 */
public class MyDateUtil {
    public static final String DEFAULT_PATTERN="yyyy/MM/dd HH:mm:ss";
    private MyDateUtil(){
    }

    /**
     * 日期转字符串
     * @param Date 要转的日期
     * @param pattern 日期模式
     * @return 字符串
     */
    public static String toFormatString(Date Date ,String pattern){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        if(!(pattern!=null&&pattern.trim().length()>0)){
            pattern=MyDateUtil.DEFAULT_PATTERN;
        }
        //确定pattern
        simpleDateFormat.applyPattern(pattern);
        //加载pattern
        return simpleDateFormat.format(Date);
    }

    /**
     * 空模式日期转字符串
     * @param Date 要转的日期
     * @return 字符串
     */
    public static String toFormatString(Date Date ){
        return toFormatString(Date,"");
    }

    /**
     * 字符串转日期
     * @param str 要转的字符串
     * @param pattern 模式
     * @return  日期
     * @throws ParseException 异常
     */
    public static Date toDate(String str,String pattern) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        if(!(pattern != null && pattern.trim().length() > 0)) {
            pattern=MyDateUtil.DEFAULT_PATTERN;
        }
        simpleDateFormat.applyPattern(pattern);
        return simpleDateFormat.parse(str);
    }
}
class Test{
    public static void main(String[] args) {
        System.out.println(MyDateUtil.toFormatString(new Date()));
        System.out.println(MyDateUtil.toFormatString(new Date(), ""));
        System.out.println(MyDateUtil.toFormatString(new Date(), "yyyy MM dd"));
        try {
            System.out.println(MyDateUtil.toDate(MyDateUtil.toFormatString(new Date(), ""), MyDateUtil.DEFAULT_PATTERN));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
